package com.clementheliou.cheliou.dal.dao.comment.impl;

import java.util.List;

import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.clementheliou.cheliou.dal.dao.comment.CommentDAO;
import com.clementheliou.cheliou.dal.dao.generic.impl.GenericHibernateDAO;
import com.clementheliou.cheliou.dal.model.comment.Comment;

/**
 * Hibernate-based implementation of the DAO dedicated to the {@link Comment} entities.
 * 
 * @author Clément HELIOU (clement.heliou@gmail.com)
 * @see {@link Comment};
 * @see {@link GenericHibernateDAO};
 * @see {@link CommentDAO};
 * @see {@link Repository}.
 * @since 1.0
 */
@Repository
public class CommentHibernateDAO extends GenericHibernateDAO<Comment> implements CommentDAO {

	/**
	 * Logger for this class.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @see {@link Logger};
	 * @see {@link LoggerFactory}.
	 * @since 1.0
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(CommentHibernateDAO.class);

	/**
	 * <i>{@inheritDoc}</i>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	public Integer countCommentsOfPhoto(final Integer photoId) {
		LOGGER.debug("Count the comments of the photo {}.", photoId);

		final StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) ");
		queryBuilder.append("FROM ").append(Comment.class.getName()).append(" AS comment ");
		queryBuilder.append("WHERE comment.commentedPhoto.id = :photoId");

		final Query query = getCurrentSession().createQuery(queryBuilder.toString());
		query.setParameter("photoId", photoId);

		return ((Long) query.uniqueResult()).intValue();
	}

	/**
	 * <i>{@inheritDoc}</i>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<Comment> getCommentsOfPhoto(final Integer photoId, final int first, final int pageSize) {
		LOGGER.debug("Get the comments of the photo {} from {} with the page size {}.", new Object[] { photoId, first, pageSize });

		final StringBuilder queryBuilder = new StringBuilder("FROM ").append(Comment.class.getName()).append(" AS comment ");
		queryBuilder.append("INNER JOIN FETCH comment.author ");
		queryBuilder.append("WHERE comment.commentedPhoto.id = :photoId ");
		queryBuilder.append("ORDER BY comment.additionDate DESC");

		final Query query = getCurrentSession().createQuery(queryBuilder.toString());
		query.setFirstResult(first);
		query.setMaxResults(pageSize);
		query.setParameter("photoId", photoId);

		return (List<Comment>) query.list();
	}
}
